package com.goldgov.conference.web;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.goldgov.conference.service.Conference;
import com.goldgov.conference.service.ConferenceAttendance;
import com.goldgov.conference.service.ConferenceAttendanceService;
import com.goldgov.conference.service.ConferenceQuery;
import com.goldgov.conference.service.ConferenceService;
import com.goldgov.conference.service.ConferenceStat;
import com.goldgov.conference.service.ConferenceStatQuery;
import com.goldgov.conference.service.ConferenceStatService;
import com.goldgov.conference.service.ConferenceUser;
import com.goldgov.conference.service.ConferenceUserQuery;
import com.goldgov.conference.service.ConferenceUserService;
import com.goldgov.kcloud.core.json.JsonErrorObject;
import com.goldgov.kcloud.core.json.JsonObject;
import com.goldgov.kcloud.core.json.JsonQueryObject;
import com.goldgov.kcloud.core.json.JsonSuccessObject;
import com.goldgov.login.web.model.LoginAuthUser;
import com.goldgov.ms.adapter.call.RemoteCallService;
import com.goldgov.notifyrecord.service.NotifyRecordService;
import com.goldgov.securityworkbench.attachment.AttachementBean;
import com.goldgov.utils.DataUtil;
import com.goldgov.utils.DateUtil;
import com.goldgov.utils.PrintUtil;
import com.goldgov.utils.PropertyUtil;
import com.goldgov.utils.UrlUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

/** 
 * @ClassName: ConferenceForPortalController 
 * @Description: TODO
 * @author hanxiangyu
 * @date 2018年6月19日 下午7:46:16 
 */
@RestController
@RequestMapping("/portal/conference")
@Api("三会一课服务接口")
public class ConferenceForPortalController {
	
	@Autowired
	private ConferenceService conferenceService;
	
	//回执/会议记录与用户关系 服务接口
	@Autowired
	private ConferenceUserService conferenceUserService;
	
	//考勤记录服务接口
	@Autowired
	private ConferenceAttendanceService conferenceAttendanceService;
	
	@Autowired
	private RemoteCallService remoteCallService;
	
	@Autowired
	private ConferenceStatService conferenceStatService;
	
	@Autowired
	private NotifyRecordService notifyRecordService;
	
	@GetMapping
	@ApiOperation(value = "查询多条会议", notes ="三会一课列表")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchConferenceType", value = "会议类型", paramType = "query"),
	 @ApiImplicitParam(name = "searchConferenceBeginDate", value = "会议开始时间", paramType = "query"),
	 @ApiImplicitParam(name = "searchConferenceName", value = "会议名称", paramType = "query"),
	 @ApiImplicitParam(name = "searchYear", value = "年份", paramType = "query"),
	 @ApiImplicitParam(name = "searchQuarter", value = "季度", paramType = "query"),
	 @ApiImplicitParam(name = "searchMeetingStatus", value = "会议状态", paramType = "query"),
	 @ApiImplicitParam(name = "searchUserId", value = "当前登录用户测试使用", paramType = "query"),
	 @ApiImplicitParam(name = "searchConferenceEndDate", value = "会议结束时间", paramType = "query")})
	public JsonQueryObject<Conference> getConferenceList(@ApiIgnore ConferenceQuery query,HttpServletRequest request,Model model){
//		String u=LoginAuthUser.getSwbUserScopeTest(request);
//		query.setSearchScopeCode(u);
//		String ip=request.getRemoteAddr();
		//当前登录的用户
		LoginAuthUser loginu=LoginAuthUser.getUser(request);
		if (query.getSearchUserId() == null || "".equals(query.getSearchUserId())) {
			query.setSearchUserId(loginu.getEntityID());
		}
		try {
			List<Conference> list = conferenceService.getConferenceList(query);
			if(null!=list && list.size()>0) {
				for(Conference c:list) {
				    Map params=new HashMap();
					params.put("groupId", c.getConferenceID());
					String resultList=remoteCallService.getForObject("fileListHandler", String.class, params);
					JSONObject json=JSONObject.parseObject(resultList).getJSONObject("data");
					JSONArray jsonList=json.getJSONArray("resultList");
					List<AttachementBean> ab=jsonList.toJavaList(AttachementBean.class);
					for(AttachementBean att:ab) {
						att.setImgUrl(UrlUtil.ATTACHEMEMENT_URL+att.getAttachid());
						if (PropertyUtil.objectNotEmpty(att.getAttachextname()) && DataUtil.isVideo(att.getAttachextname())) {
							att.setDefaultVideoUrl(DataUtil.videoImgUrl(att.getAttachid()));
						}else {
							att.setDefaultVideoUrl(UrlUtil.ATTACHEMEMENT_URL+AttachementBean.DEFAULT_VIDEO_ID);
						}
					}
					c.setFileList(ab);
				}
			}
			query.setResultList(list);
			model.addAttribute("msg", "成功");
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", "失败");
		}		
		return new JsonQueryObject<>(query);
	}
	
	
	@PutMapping("/updateReceipt")
	@ApiOperation(value = "回执操作/请假", notes ="对三会一课的回执操作")
	public void updateReceipt(ConferenceUser obj,HttpServletRequest request,HttpServletResponse response,Model model){
		//回执时间
		LoginAuthUser u=LoginAuthUser.getUser(request);
		if (obj.getUserID() == null || "".equals(obj.getUserID())) {
			obj.setUserID(u.getEntityID());
		}
		obj.setReceiptDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		conferenceUserService.updateReceipt(obj);
		ConferenceUser cu = conferenceUserService.getConferenceUser(obj);
		try {
			if (null != obj.getReceiptType() && obj.getReceiptType() == 3) {
//				Conference conference = new Conference();
//				conference.setConferenceID(obj.getConferenceID());
//				conference.setQjNum(1);
//				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//				conference.setLastModifiedDate(sdf.format(new Date()));
//				conferenceService.updateConference(conference);
				//通过关系表id确定是否存在考勤记录
				List<ConferenceAttendance> attendanceList = conferenceAttendanceService.getConferenceAttendanceList(cu.getConferenceUserID());
				if (!attendanceList.isEmpty()) {
//					Conference c = new Conference();
//					c.setConferenceID(obj.getConferenceID());
//					c.setYqNum(1);
//					conferenceService.updateNum(c);
					conferenceAttendanceService.deleteConferenceAttendance(cu.getConferenceUserID());
				}
			}
			PrintUtil.print(response, true);
		} catch (Exception e) {
			PrintUtil.print(response, false);
			e.printStackTrace();
		}
	}
	@PostMapping("/addAttendance")
	@ApiOperation(value = "考勤记录", notes ="对三会一课的考勤记录")
	public void addAttendance(ConferenceAttendance obj,HttpServletRequest request,HttpServletResponse response){
		LoginAuthUser u=LoginAuthUser.getUser(request);
		if (obj.getUserID() == null || "".equals(obj.getUserID())) {
			obj.setUserID(u.getEntityID());
//			obj.setUserID(obj.getUserID());
		}
		obj.setAttendanceDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		if (obj.getAttendanceStatus() == null) {
			obj.setAttendanceStatus(ConferenceQuery.STATUS_YQ);
		}
		//获取用户与记录的关系表 存入考勤表中
		ConferenceUser conferenceUser = new ConferenceUser();
		conferenceUser.setConferenceID(obj.getConferenceID());
		conferenceUser.setUserID(obj.getUserID());
		ConferenceUser cu = conferenceUserService.getConferenceUser(conferenceUser);
		//签到时更新一下回执表,以防存在请假
		if (cu.getReceiptType() != null && cu.getReceiptType() == 3) {
			conferenceUser.setReceiptType(ConferenceQuery.STATUS_YQ);
			conferenceUserService.updateReceipt(conferenceUser);
//			Conference c = new Conference();
//			c.setConferenceID(obj.getConferenceID());
//			c.setQjNum(ConferenceQuery.ONE);
//			conferenceService.updateNum(c);
		}
		//通过关系表id确定是否存在考勤记录
		List<ConferenceAttendance> attendanceList = conferenceAttendanceService.getConferenceAttendanceList(cu.getConferenceUserID());
		//只存在一条考勤记录时
		try {
			if (attendanceList.isEmpty()) {//判断是否有考勤记录如不存在考勤记录更新会议表考勤数+1
//				Conference conference = new Conference();
//				conference.setConferenceID(obj.getConferenceID());
//				conference.setYqNum(ConferenceQuery.ONE);
//				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//				conference.setLastModifiedDate(sdf.format(new Date()));
//				conferenceService.updateConference(conference);
				obj.setConferenceUserID(cu.getConferenceUserID());
				conferenceAttendanceService.addConferenceAttendance(obj);
			}else {
				obj.setConferenceUserID(cu.getConferenceUserID());
				conferenceAttendanceService.updateConferenceAttendance(obj);
			}
			PrintUtil.print(response, true);
		} catch (Exception e) {
			PrintUtil.print(response, false);
			e.printStackTrace();
		}
	}
	
	@GetMapping("/{id}")
	@ApiOperation(value = "根据主键查询会议记录", notes ="工作日志详情")
	public JsonSuccessObject<Conference> getConference(Model model,@ApiParam(value="conferenceID",required=false) @PathVariable("id") String id,HttpServletRequest request){
		Conference obj = new Conference();
		obj.setConferenceID(id);
		LoginAuthUser u=LoginAuthUser.getUser(request);
		obj.setUserID(u.getEntityID());
		Conference conference = conferenceService.getConference(obj);
		//获取附件信息
		Map params=new HashMap();
		params.put("groupId", conference.getConferenceID());
		String resultList=remoteCallService.getForObject("fileListHandler", String.class, params);
		JSONObject json=JSONObject.parseObject(resultList).getJSONObject("data");
		JSONArray jsonList=json.getJSONArray("resultList");
		List<AttachementBean> ab=jsonList.toJavaList(AttachementBean.class);
		for(AttachementBean att:ab) {
			att.setImgUrl(UrlUtil.ATTACHEMEMENT_URL+att.getAttachid());
			if (PropertyUtil.objectNotEmpty(att.getAttachextname()) && DataUtil.isVideo(att.getAttachextname())) {
				att.setDefaultVideoUrl(DataUtil.videoImgUrl(att.getAttachid()));
			}else {
				att.setDefaultVideoUrl(UrlUtil.ATTACHEMEMENT_URL+AttachementBean.DEFAULT_VIDEO_ID);
			}
		}
		conference.setFileList(ab);
		//获取请假人员列表
		List<ConferenceUser> qjList=conferenceUserService.getConferenceUserQjList(id);
		conference.setQjList(qjList);
		//获取缺席人员列表
		List<ConferenceUser> qxList=conferenceUserService.getConferenceUserQxList(id);
		conference.setQxList(qxList);
		//获取考勤人员列表
		List<ConferenceUser> qdList = conferenceUserService.getConferenceUserQdList(id);
		if (!qdList.isEmpty()) {
			conference.setQdList(qdList);
		}
		//获取出席人列表
		List<ConferenceUser> cxList = conferenceUserService.getConferenceUserCxList(id);
		conference.setConferenceUserList(cxList);
		JsonSuccessObject<Conference> returnResult = new JsonSuccessObject<>(conference);
		return returnResult;
	}
	@GetMapping("/listGetConference")
	@ApiOperation(value = "获取会议出席人列表", notes ="出席人列表查询")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchConferenceID", value = "会议id", paramType = "query")})
	public JsonQueryObject<ConferenceUser> getConferenceList(@ApiIgnore ConferenceUserQuery query,HttpServletRequest request,Model model){
		try {
			List<ConferenceUser> userList = conferenceUserService.getConferenceUserList(query);
			query.setResultList(userList);
			model.addAttribute("msg", "成功");
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("msg", "失败");
		}
		return new JsonQueryObject<>(query);
	}
	/**
	 * @date 2018年6月25日 上午9:42:05 
	 * @author hanxiangyu
	 * @param conferenceStat
	 * @param request
	 * @param model
	 * @return
	 */
	@GetMapping("/getPartyOrganizationRank")
	@ApiOperation(value = "三会一课统计", notes ="三会一课统计同级支部统计")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchBeginDate", value = "开始时间", paramType = "query"),
		 @ApiImplicitParam(name = "searchEndDate", value = "结束时间", paramType = "query"),
		 @ApiImplicitParam(name = "searchPartyBranch", value = "所在党支部", paramType = "query"),
		 @ApiImplicitParam(name = "searchYear", value = "年份", paramType = "query"),
		 @ApiImplicitParam(name = "searchType", value = "类型", paramType = "query"),
		 @ApiImplicitParam(name = "searchQuarter", value = "季度", paramType = "query")})
	public JsonQueryObject<ConferenceStat> getPartyOrganizationRank(@ApiIgnore ConferenceStatQuery query,HttpServletRequest request,Model model){
		String u=LoginAuthUser.getPortalUserScope(request);//前台获去code
		query.setSearchScopeCode(u);
		LoginAuthUser user = LoginAuthUser.getUser(request);
		query.setSearchUserID(user.getEntityID());
		if (query.getSearchYear() == null || "".equals(query.getSearchYear())) {
			query.setSearchYear(String.valueOf(DateUtil.getYear(new Date())));
		}
		List<ConferenceStat> list =null;
//		Integer isManager=Integer.valueOf(request.getParameter("isUserAdmin"));
//		if(null!=isManager && isManager==1) {//管理员查询
//			list = conferenceStatService.getPartyOrganizationByAdmin(query);
//		}else {
			list = conferenceStatService.getPortalPartyORankStat(query);
//		}
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}
	
	@GetMapping("/getPartyOrganizationLife")
	@ApiOperation(value = "本支部组织生活统计分析", notes ="获取本支部组织生活统计分析情况")
	public JsonSuccessObject<ConferenceStat> getPartyOrganizationLife(ConferenceStat conferenceStat,HttpServletRequest request,Model model){
//		String u=LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request);
//		String u=LoginAuthUser.getPortalUserScope(request);
//		conferenceStat.setScopeCode(u);
		LoginAuthUser user = LoginAuthUser.getUser(request);
		conferenceStat.setUserID(user.getEntityID());
		if (conferenceStat.getYear() == null || "".equals(conferenceStat.getYear())) {
			conferenceStat.setYear(String.valueOf(DateUtil.getYear(new Date())));
		}
		ConferenceStat partyOrganizationLife = conferenceStatService.getPortalPartyBranchStat(conferenceStat);
		JsonSuccessObject<ConferenceStat> returnResult = new JsonSuccessObject<>(partyOrganizationLife);
		return returnResult;
	}
	@GetMapping("/getAttenanceStat")
	@ApiOperation(value = "出勤情况统计", notes ="当前登录人考勤情况统计")
	public JsonSuccessObject<ConferenceStat> getAttenanceStat(ConferenceStat conferenceStat,HttpServletRequest request,Model model){
		LoginAuthUser loginu=LoginAuthUser.getUser(request);
		String scope = LoginAuthUser.getPortalUserScope(request);
		conferenceStat.setScopeCode(scope);
		if (conferenceStat.getUserID() == null || "".equals(conferenceStat.getUserID())) {
			conferenceStat.setUserID(loginu.getEntityID());
		}
		if (conferenceStat.getYear() == null || "".equals(conferenceStat.getYear())) {
			conferenceStat.setYear(String.valueOf(DateUtil.getYear(new Date())));
		}
		ConferenceStat attenanceStat = conferenceStatService.getAttenanceStat(conferenceStat);
		JsonSuccessObject<ConferenceStat> returnResult = new JsonSuccessObject<>(attenanceStat);
		return returnResult;
	}
	
}
